// pages/activity/seckill/index.js
const service = require("../../../../service/activity")
const utils = require("../../../../utils/util")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timelist: [],
    timeData: {},
    swiperList: 4,
    swiperIdx: 0,
    chooseClass: false,
    seckillnow: true,
    pageNum: 1, // 当前请求的page
    pageSize: 1000, // 请求数据的size
    nomoredata: false,
    startTime: "",
    endTime: "",
    seckillListSwiper: [],
    seckillList: [],
    orderList: [],
    countDownText: "本场还剩 ",
    noDatas: false
  },
  onChange(e) {
    //console.log(e);
    this.setData({
      timeData: e.detail,
    });
    if (e.detail.hours == 0 && e.detail.minutes == 0 && e.detail.seconds == 0) {
      this.onLoad()
    }
  },
  bindchange(e) {
    this.setData({
      swiperIdx: e.detail.current
    })
  },
  chooseTime(e) {

    this.setData({
      chooseClass: e.currentTarget.dataset.index,
      startTime: e.currentTarget.dataset.info.startTimes,
      endTime: e.currentTarget.dataset.info.endTimes,
      pageNum: 1,
      chooseText: e.currentTarget.dataset.info.text
    });
    this.getcurrentList()
  },
  getcurrentList() {
    this.SeckillSkuList((res) => {
      console.log(res);
      if (res.code == "00000") {

        if (res.data.rows.length == 0) {
          this.setData({
            orderList: res.data.rows,
            nomoredata: false,
            noDatas: true
          })
        } else {
          this.setData({
            orderList: res.data.rows,
            nomoredata: false,
            noDatas: false
          })
        }
      }

    })

  },
  SeckillSkuList(callback) {
    wx.showLoading({
      title: "加载中...",
    });
    service.getSeckillSkuList({
      //列表参数
      "data": {
        "startTimes": this.data.startTime,
        "endTimes": this.data.endTime,
        "isPaging": 1,
        "customerId": wx.getStorageSync('userInfo').id
      },
      "queryRequest": {
        "pageSize": this.data.pageSize,
        "pageNum": this.data.pageNum
      }
    }, res => {
      wx.hideLoading();
      for (let i = 0; i < res.data.rows.length; i++) {
        const element = res.data.rows[i];
        var img = JSON.parse(element.image)
        var url = img.temBanner.split(",");
        element.url = url[0];
      }
      callback(res)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  formateTime(time) {
    var t = new Date(time.replace(/-/g, '/'));
    var times = t.getHours() + ":00";
    var huor = t.getHours();
    if (huor < 10) {
      huor = "0" + huor;
    }
    var item = {};
    item.time = times;
    item.startTimes = this.Datetime() + " " + huor + ":00:00";
    item.endTimes = this.Datetime() + " " + huor + ":59:59";
    item.text = parseInt(huor) == new Date().getHours() ? "正在疯抢" : "即将秒杀"

    return item
  },
  onLoad: function (options) {


    service.getTimeList({
      "startTimes": this.Datetime() + " " + "00:00:01",
      "endTimes": this.Datetime() + " " + "23:59:59",
    }, res => {
      console.log(res);
      if (res.data.length == 0) {
        this.setData({
          noDatas: true
        })
        return
      };
      var list = [];
      for (let i = 0; i < res.data.length; i++) {
        const element = res.data[i];
        var startTimes = new Date(element.startTime.replace(/-/g, '/') + ":00:00").getTime();
        var endTimes = new Date(element.endTime.replace(/-/g, '/') + ":00:00").getTime();
        var item = {}
        item.time = element.startTime.substring(element.startTime.length - 2) + ":00";
        item.startTimes = element.startTime + ":00:00"
        item.endTimes = element.endTime + ":00:00"
        item.text = "即将秒杀"

        list.push(item)
        this.setData({
          timelist: list,
        })

      }
      this.setData({
        startTime: this.data.timelist[0].startTimes,
        endTime: this.data.timelist[0].endTimes,
        chooseClass: 0,
        pageNum: 1,
        chooseText: this.data.timelist[0].text
      })
      this.getcurrentList();


    })


    // service.getsecTime(res => {
    //   console.log(res)
    //   var t = new Date(res.data);
    //   var huor = t.getHours();
    //   var timelist = this.data.timelist;

    //   var num = 24 - huor;
    //   var i = 0;
    //   var gettimelist=() => {
    //     if (num > 0) {
    //       timelist.push(this.formateTime(this.Datetime() + " " + (huor + i) + ":00:00"))
    //       this.setData({
    //         timelist: timelist
    //       })
    //       console.log(this.data.timelist,"sss");
    //       num--;
    //       i++;
    //       gettimelist()
    //     } else {
    //       console.log(this.data.timelist,"hhh");
    //       this.setData({
    //         startTime: this.data.timelist[0].startTimes,
    //         endTime: this.data.timelist[0].endTimes,
    //         time: new Date(this.data.timelist[1].startTimes).getTime() - t.getTime()
    //       })
    //       this.SeckillSkuList(res => {
    //         console.log(res)
    //         if (this.data.seckillnow) {
    //           if (res.data.rows.length == 0) {
    //             this.setData({
    //               seckillListSwiper: [],
    //               seckillList: [],
    //               nomoredata: false,
    //               noDatas: true
    //             })
    //           } else {
    //             for (let i = 0; i < res.data.rows.length; i++) {
    //               const element = res.data.rows[i];
    //               element.percent = (element.seckillStock - element.seckillStockNow) / element.seckillStock * 100
    //             }
    //             this.setData({
    //               seckillListSwiper: res.data.rows.slice(0, 4),
    //               seckillList: res.data.rows.slice(4, -1),
    //               nomoredata: false,
    //               noDatas: false
    //             })
    //           }
    //         } else {
    //           if (res.data.rows.length == 0) {
    //             this.setData({
    //               orderList: res.data.rows,
    //               nomoredata: false,
    //               noDatas: true
    //             })
    //           } else {
    //             this.setData({
    //               orderList: res.data.rows,
    //               nomoredata: false,
    //               noDatas: false
    //             })
    //           }
    //         }
    //       })
    //     }

    //   }
    //   gettimelist()
    //   // for (let i = 0; i < (24 - huor); i++) {
    //   //   timelist.push(this.formateTime(this.Datetime() + " " + (huor + i) + ":00:00"))
    //   //   this.setData({
    //   //     timelist: timelist
    //   //   })
    //   // }





    // })
  },

  Datetime() {
    var myDate = new Date;

    myDate.setDate(myDate.getDate() + 1); //获取明日
    console.log(myDate.format("yyyy-MM-dd"))
    return myDate.format("yyyy-MM-dd");
    // var h = myDate.getHours(); //获取当前小时数(0-23)		
    // if (mon <= 10 && date <= 10) {
    //   return (year + "-0" + mon + "-0" + date);
    // }
    // if (mon < 10 && date > 10) {
    //   return (year + "-0" + mon + "-" + date);
    // }
    // if (mon >= 10 && date > 10) {
    //   return (year + "-" + mon + "-" + date);
    // }
    // if (mon >= 10 && date < 10) {
    //   return (year + "-" + mon + "-0" + date);
    // }
  },
  godetail(e) {
    var time = "";
    if (e.currentTarget.dataset.status == false) {
      time = this.data.startTime
    } else {
      time = this.data.endTime
    }
    wx.navigateTo({
      url: '/pages/activity/goodDetail/index?id=' + e.currentTarget.dataset.info.id + "&endTime=" + time + "&status=" + e.currentTarget.dataset.status,
    })
  },
  subscribeTo(e) {

    let self = this

    // let startTime = e.currentTarget.dataset.index.startTime.replace(/\s|-|:/g, "")
    let groupId = e.currentTarget.dataset.index.seckillId
    let skuId = e.currentTarget.dataset.index.skuId
    service.getTemplateId((response)=>{
      wx.requestSubscribeMessage({
        tmplIds: [response.data],
        success(res) {
          if (res[response.data] == "accept") {
            service.groupActivitiesUserAppointment({
              "skuName": e.currentTarget.dataset.index.title,
              "groupName": e.currentTarget.dataset.index.title,
              "customerId": wx.getStorageSync('userInfo').id,
              "startTime": self.data.startTime,
              "touser": wx.getStorageSync('userInfo').openId,
              "skuId": skuId,
              "groupId": groupId,
              "url": '/pages/activity/seckill/index'
            }, res => {
              console.log(res)
              if (res.code == "00000") {
                wx.showToast({
                  title: '订阅成功',
                  icon: 'success',
                  duration: 2000
                })
                self.onLoad()
              }
            })
          }
        }
      })
    })
  
  },
  back() {
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      pageNum: 1,
      nomoredata: false,
      noDatas: false
    });
    const self = this;

    this.SeckillSkuList(function (res) {
      console.log(res);
      
      if (res.code == "00000") {
        
        if (self.data.seckillnow) {
          if (res.data.rows.length == 0) {
            self.setData({
              seckillListSwiper: [],
              seckillList: [],
              nomoredata: false,
              noDatas: true
            })
          } else {
            self.setData({
              seckillListSwiper: res.data.rows.slice(0, 4),
              seckillList: res.data.rows.slice(4, -1),
              nomoredata: false,
              noDatas: false
            })
          }
        } else {
          if (res.data.rows.length == 0) {
            self.setData({
              orderList: res.data.rows,
              nomoredata: false,
              noDatas: true
            })
          } else {
            
            self.setData({
              orderList: res.data.rows,
              nomoredata: false,
              noDatas: false
            })
          }
        }

      }

      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.noData) return;
    wx.stopPullDownRefresh();

    var seckilllist = this.data.seckillList;
    var orderList = this.data.orderList;
    let page = this.data.pageNum;
    this.setData({
      // 每次下拉 page+1
      pageNum: ++page,
    });
    const self = this;

    this.SeckillSkuList(function (res) {
      if (self.data.seckillnow) {
        if (res.data.rows.length == 0) {
          self.setData({
            nomoredata: true,
            noDatas: false
          });
        } else {
          res.data.rows.forEach((item) => {

            seckilllist.push(item);
          });
          self.setData({
            seckillList: seckilllist,
            nomoredata: false,
            noDatas: false
          });
        }
      } else {
        if (res.data.rows.length == 0) {
          self.setData({

            nomoredata: true,
            noDatas: false
          })
        } else {
          res.data.rows.forEach((item) => {

            orderList.push(item);
          });
          self.setData({
            orderList: orderList,
            nomoredata: false,
            noDatas: false
          });
        }
      }


      // 隐藏加载状态
      // wx.hideNavigationBarLoading()
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})